package com.loveshes.filter;

import com.loveshes.constants.Constants;
import com.loveshes.util.IdUtil;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;

import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;

/**
 * @author wangz4
 * @date 2024/12/26 20:18
 */
@Activate(group = CONSUMER, order = Integer.MIN_VALUE + 1000)
public class ReqNoConsumerFilter implements Filter, Filter.Listener {
    
    // TODO 客户端拿不到reqTraceId，Why？
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        // 生成序列号
        String reqTraceId = IdUtil.generateTraceId();
        // 将序列号值设置到上下文对象中
        invocation.setAttachment(Constants.MDC_KEY_TRACE_ID, reqTraceId);
        RpcContext.getClientAttachment().setAttachment(Constants.MDC_KEY_TRACE_ID, reqTraceId);
        try {
            // 并且将序列号设置到日志打印器中，方便在日志中体现出来
            MDC.put(Constants.MDC_KEY_TRACE_ID, reqTraceId);
            // 继续后面过滤器的调用
            return invoker.invoke(invocation);
        } finally {
            MDC.clear();
        }
    }
    
    @Override
    public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
    }
    
    @Override
    public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
    }
    
    
}
